package com.dpiinc.TechPage.user.utils

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.FileProvider
import cn.sharesdk.onekeyshare.OnekeyShare
import cn.sharesdk.sina.weibo.SinaWeibo
import cn.sharesdk.system.email.Email
import cn.sharesdk.tencent.qq.QQ
import cn.sharesdk.wechat.friends.Wechat
import cn.sharesdk.wechat.moments.WechatMoments
import com.dpiinc.TechPage.AIWriteApplication.Companion.instance
import com.dpiinc.TechPage.R
import com.tqltech.tqlpencomm.util.BLEFileUtil.mContext
import java.io.File


/**
 * Created by hu489_000 on 2018-07-14.
 */
object ShareHelper {
    const val TAG = "ShareHelper"
    fun showShareDialog(context: Context, list: ArrayList<String>,hdrText : String) {
        val bottomDialog = Dialog(context, R.style.BottomDialog)
        val contentView = LayoutInflater.from(context).inflate(R.layout.share_pop, null)
        bottomDialog.setContentView(contentView)
        val layoutParams = contentView.layoutParams
        layoutParams.width = context.resources.displayMetrics.widthPixels
        contentView.layoutParams = layoutParams
        bottomDialog.window!!.setGravity(Gravity.BOTTOM)
        bottomDialog.show()
        val share_wechat = contentView.findViewById(R.id.share_wechat) as View
        share_wechat.setOnClickListener {
            if (!TextUtils.isEmpty(hdrText)) {
                showShareTxt(context, Wechat.NAME,hdrText)
            } else {
                showShare(context, Wechat.NAME)
            }
            bottomDialog.dismiss()
        }
        val share_wechat_time = contentView.findViewById(R.id.share_wechat_time) as View
        share_wechat_time.setOnClickListener {
            if (!TextUtils.isEmpty(hdrText)) {
                showShareTxt(context, WechatMoments.NAME,hdrText)
            } else {
                showShare(context, WechatMoments.NAME)
            }
            bottomDialog.dismiss()
        }
        val share_qq = contentView.findViewById(R.id.share_qq) as View
        val share_txt = contentView.findViewById(R.id.share_txt) as View
        val share_download = contentView.findViewById(R.id.share_download) as View
        if (!TextUtils.isEmpty(hdrText)) {//不为空表示是识别页面调用
            share_txt.visibility = View.VISIBLE
            share_qq.visibility = View.GONE
            share_download.visibility = View.GONE
        } else {
            share_txt.visibility = View.GONE
            share_qq.visibility = View.VISIBLE
            share_download.visibility = View.VISIBLE
        }
        share_qq.setOnClickListener {
            if (!TextUtils.isEmpty(hdrText)) {
                //showShare(context)
                showShareTxt(context, QQ.NAME,hdrText)
            } else {
                showShare(context, QQ.NAME)
            }
            bottomDialog.dismiss()
        }
        val share_weibo = contentView.findViewById(R.id.share_weibo) as View
        share_weibo.setOnClickListener {
            if (!TextUtils.isEmpty(hdrText)) {
                showShareTxt(context, SinaWeibo.NAME,hdrText)
            } else {
                showShare(context, SinaWeibo.NAME)
            }
            bottomDialog.dismiss()
        }
        val share_email = contentView.findViewById(R.id.share_email) as View
        share_email.setOnClickListener {
            if (!TextUtils.isEmpty(hdrText)) {//不为空表示是识别页面调用
                showShareTxt(context, Email.NAME,hdrText)
            } else {
                showShare(context, Email.NAME)
            }
            bottomDialog.dismiss()
        }
        share_download.setOnClickListener {
            if (ViewToBitmapUtil.saveBitmapToGallery(context)) {
               // ToastUtils.showCenterTip(context, context.getString(R.string.save_img_success))
            }
            bottomDialog.dismiss()
            sharePictureFile(context)
        }
        val share_pdf = contentView.findViewById(R.id.share_pdf) as View
        share_pdf.setOnClickListener {
            if (!TextUtils.isEmpty(hdrText)) {
                ViewToBitmapUtil.saveToNewPDF(hdrText)
            } else {
                   if (ViewToBitmapUtil.saveToPDF(context, list)) {
                  // ToastUtils.showCenterTip(context, context.getString(R.string.save_pdf_success))
               }
            }

            bottomDialog.dismiss()
            sharePDFFile(context)
        }

        share_txt.setOnClickListener {
            ViewToBitmapUtil.saveToTxt(hdrText)
            bottomDialog.dismiss()
            shareTXTFileSystem(context)
        }
    }
    /**
     * 调用系统分享图片
     */
    private fun sharePictureFile(context: Context) {
       // val path = Environment.getExternalStorageDirectory().canonicalPath + "/vBand/66.png"
/*        val path = context.getExternalFilesDir(null)?.canonicalPath + "/vBand/66.png"
        val file = File(path)*/
        val file = File(ViewToBitmapUtil.share_file)
        Log.e(TAG,"路径===>"+ViewToBitmapUtil.share_file)
        //由文件得到uri
        val currentApiVersion = Build.VERSION.SDK_INT
        val imageUri: Uri = if (currentApiVersion >= 24) {
            //Log.e(TAG, "版本大于24，获取uri采用共享文件模式, 根目录：" +  Environment.getExternalStorageDirectory().getPath());
            FileProvider.getUriForFile(context, "com.dpiinc.TechPage.provider", file)
        } else {
            Uri.fromFile(file)
        }
        val shareIntent = Intent()
        shareIntent.action = Intent.ACTION_SEND
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri)
        shareIntent.type = "image/*"
        context.startActivity(Intent.createChooser(shareIntent, "share:"))
    }

    /**
     * 调用系统分享图片
     */
    private fun sharePDFFile(context: Context) {
        if (!TextUtils.isEmpty(ViewToBitmapUtil.pdf)) {
            val file = File(ViewToBitmapUtil.pdf)
            Log.e(TAG, "路径===>" + ViewToBitmapUtil.pdf)
            //由文件得到uri
            val currentApiVersion = Build.VERSION.SDK_INT
            val imageUri: Uri = if (currentApiVersion >= 24) {
                //Log.e(TAG, "版本大于24，获取uri采用共享文件模式, 根目录：" +  Environment.getExternalStorageDirectory().getPath());
                FileProvider.getUriForFile(context, "com.dpiinc.TechPage.provider", file)
            } else {
                Uri.fromFile(file)
            }
            val shareIntent = Intent()
            shareIntent.action = Intent.ACTION_SEND
            shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri)
            shareIntent.type = "application/pdf"
            context.startActivity(Intent.createChooser(shareIntent, "share:"))
        }
    }

    fun showShare(context: Context?, platform: String?) {
        val oks = OnekeyShare()
        //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
        if (platform != null) {
            oks.setPlatform(platform)
        }
        //关闭sso授权
        oks.disableSSOWhenAuthorize()
        if (platform != QQ.NAME) {
            // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
            oks.setTitle(instance().resources.getString(R.string.app_share))
// text是分享文本，所有平台都需要这个字段
            oks.text = instance().resources.getString(R.string.app_share)
        }
//        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
//        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        val path = ViewToBitmapUtil.share_file
        Log.d(TAG, "path = $path")
        oks.setImagePath(path) //确保SDcard下面存在此张图片

        // url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl("http://sharesdk.cn");
//        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
//        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite("ShareSDK");
//        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl("http://sharesdk.cn");
        //启动分享
        oks.show(context)
    }

    private fun showShareTxt(context: Context, platform: String?,hdrText: String) {
        val oks = OnekeyShare()
        //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
        if (platform != null) {
            oks.setPlatform(platform)
        }
        //关闭sso授权
        oks.disableSSOWhenAuthorize()
        oks.text = hdrText
        //启动分享
        oks.show(context)
    }

    /**
     * 调用系统分享txt
     */
    private fun shareTXTFileSystem(context: Context) {
        if (!TextUtils.isEmpty(ViewToBitmapUtil.share_txt)) {
            val file = File(ViewToBitmapUtil.share_txt)
            //由文件得到uri
            val currentApiVersion = Build.VERSION.SDK_INT
            val imageUri: Uri = if (currentApiVersion >= 24) {
                FileProvider.getUriForFile(context, "com.dpiinc.TechPage.provider", file)
            } else {
                Uri.fromFile(file)
            }
            val shareIntent = Intent()
            shareIntent.action = Intent.ACTION_SEND
            shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri)
            shareIntent.type = "application/txt"
            context.startActivity(Intent.createChooser(shareIntent, "share:"))
        }
    }
}